package cn.angis.db.controller;

import cn.angis.common.api.ApiErrorCode;
import cn.angis.common.api.IErrorCode;
import cn.angis.common.constant.DatePattern;
import cn.angis.common.model.R;
import cn.angis.common.util.SystemType;
import cn.dev33.satoken.stp.StpUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.noear.solon.cloud.CloudClient;
import org.noear.solon.cloud.model.Media;
import org.noear.solon.core.handle.UploadedFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;

/**
 * 包名称：cn.angis.db.model
 * 类名称：BaseService
 * 类描述：公共controller
 * 创建人：@author angis.cn
 * 创建日期： 2022/11/28 11:38
 */
public class RBaseController {

    /**
     * 获取用户id
     */
    protected String getUserId() {
        return StpUtil.getLoginId().toString();
    }

    protected <T> R<T> success() {
        return R.restResult(ApiErrorCode.SUCCESS, null);
    }

    protected <T> R<T> success(T obj) {
        return R.success(obj);
    }

    protected <T> R<T> error(String msg) {
        return R.error(msg);
    }

    protected <T> R<T> error(IErrorCode errorCode, T obj) {
        return R.error(errorCode);
    }

    protected <T> R<T> restResult(IErrorCode errorCode, T data) {
        return R.restResult(errorCode, data);
    }

    protected R<Object> upload(UploadedFile file, String userPath) {
        String fileSavePath = System.getProperty("user.dir") + File.separator + "upload";
        Set<PosixFilePermission> perms = null;
        if (SystemType.isLinux()) {
            perms = new HashSet<PosixFilePermission>();
            perms.add(PosixFilePermission.OWNER_READ);//设置所有者的读取权限
            perms.add(PosixFilePermission.OWNER_WRITE);//设置所有者的写权限
            perms.add(PosixFilePermission.OWNER_EXECUTE);//设置所有者的执行权限
            perms.add(PosixFilePermission.GROUP_READ);//设置组的读取权限
            perms.add(PosixFilePermission.GROUP_EXECUTE);//设置组的读取权限
            perms.add(PosixFilePermission.OTHERS_READ);//设置其他的读取权限
            perms.add(PosixFilePermission.OTHERS_EXECUTE);//设置其他的读取权限
        }

        Map<String, Object> result = new HashMap<>();
        String dirDate = userPath + File.separator + DatePattern.SIMPLE_MONTH_FORMAT.format(new Date());
        File dir = new File(fileSavePath + File.separator + dirDate);
        if (!dir.exists())// 目录不存在则创建
            dir.mkdirs();
        String fileNames = "";
        try {
            if (SystemType.isLinux()) {
                Path path = Paths.get(dir.getAbsolutePath());
                Files.setPosixFilePermissions(path, perms);
            }
            String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

            String fileNameNew = dirDate + File.separator + System.currentTimeMillis() + "." + suffix;
            File tagetFile = new File(fileSavePath + File.separator + fileNameNew);
            fileNames = fileNameNew;
            tagetFile.createNewFile();
            // 保存文件到硬盘
            if ("jpgpnggifbmpjpeg".indexOf(suffix)>-1) {
                Thumbnails.of(file.getContent())
                        .scale(1f)
                        .outputQuality(0.75f).toFile(tagetFile);

            } else {
                file.transferTo(tagetFile);
            }
            Path filepath = Paths.get(tagetFile.getAbsolutePath());
            if (SystemType.isLinux()) {
                Files.setPosixFilePermissions(filepath, perms);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return success(fileNames);
    }

    protected R<Object> uploadOss(UploadedFile file, String userPath) {
        String key = userPath + "-" + System.currentTimeMillis() + file.getName();
        //上传媒体
        CloudClient.file().put(key, new Media(file.getContent(), file.getContentType()));
        return success(key);
    }

    protected Media downOss(String key) {
        return CloudClient.file().get(key);
    }

    protected String base64ToImage(String file, String path){
        // 解密
        try {
            // 项目绝对路径
            String savePath = System.getProperty("user.dir") + File.separator + "upload" + File.separator;
            // 图片分类路径+图片名+图片后缀
            String imgClassPath = path.concat(System.currentTimeMillis() + "").concat(".jpg");
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            file = file.substring(file.indexOf(",", 1) + 1, file.length());
            byte[] b = decoder.decode(file);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            OutputStream out = new FileOutputStream(savePath.concat(imgClassPath));
            out.write(b);
            out.flush();
            out.close();
            //上传媒体
            CloudClient.file().put(imgClassPath, new Media(new FileInputStream(new File(savePath.concat(imgClassPath))), "image/jpeg"));
            return imgClassPath;
        } catch (IOException e) {
            return null;
        }
    }

}
